
package fmu.pi.view.draw.old;

import fmu.pi.model.bean.Cartao;
import javafx.scene.layout.GridPane; 
import javafx.scene.layout.BorderPane; 
import javafx.scene.control.TextField; 
import javafx.scene.control.TableView; 
import javafx.scene.control.TableColumn; 
import javafx.scene.control.Label; 
import javafx.scene.control.TableCell; 
import javafx.scene.control.ChoiceBox; 
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle; 
import javafx.scene.text.Font;
import java.util.ArrayList; 
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import fmu.pi.view.handler.HandlerView; 
import javax.swing.JOptionPane;

public class CadastraCartao extends BorderPane
{
    private TextField bandeiraTextField; 
    private TextField codigoTextField;
    private TextField limiteTextField; 
    private TextField alteraBandeiraTextField; 
    private TextField alteraCodigoTextField; 
    private TextField alteraLimiteTextField;  
    private TableView tableCard; 
    private Button alteraButton; 
    private Button saveButton; 
    private Button cancelaButton; 
    private Button deletaButton; 
    private GridPane gridAlteraCartao; 
    private HandlerView handler; 
    private Cartao cardSelected; 
    
    
    public CadastraCartao()
    {
        initPane(); 
    }
    
    private void initPane()
    {
        handler = new HandlerView();
        setCenter(pane()); 
    }
    
    private GridPane pane()
    {
        GridPane grid = new GridPane(); 
        grid.setAlignment(Pos.CENTER); 
        grid.setHgap(10); 
        
        Label tableLabel = new Label(); 
        tableLabel.setText("Cartões"); 
        tableLabel.setFont(Font.font("Ariel Black", 20)); 
        tableLabel.setTextFill(Color.BLUE);
                 
        tableCard = createTableCard();
        gridAlteraCartao = alteraCartao(); 
        
        grid.add(tableLabel, 1, 0); 
        grid.add(gridFormCartao(), 0, 1); 
        grid.add(tableCard, 1, 1);
        grid.add(gridAlteraCartao, 1, 2);
        
        
        return grid; 
    }
    
    //Formulario de cadastro de cartão
    private GridPane gridFormCartao()       
    {
        GridPane grid = new GridPane(); 
        //configura o grid
        grid.setHgap(10); 
        grid.setVgap(10);
         
        for(int i = 0; i < 5; i++) //segunda coluna
            grid.add(new Rectangle(50, 30, Color.TRANSPARENT), 1, i);
        
        for(int i = 0; i < 5; i++) //terceira coluna
            grid.add(new Rectangle(250, 30, Color.TRANSPARENT), 2, i); 
        
        //Cria Label para identificação de campos e add ao grid
        Label bandeiraLabel = new Label(); 
        bandeiraLabel.setText("Nome do Cartão"); 
        bandeiraLabel.setFont(Font.font("Ariel Black", 15));
        bandeiraLabel.setTextFill(Color.BLUE); 
        grid.add(bandeiraLabel, 1, 1); 
        
        Label numberLabel = new Label(); 
        numberLabel.setText("Número do Cartão"); 
        numberLabel.setFont(Font.font("Ariel Black", 15)); 
        numberLabel.setTextFill(Color.BLUE); 
        grid.add(numberLabel, 1, 2); 
        
        Label limiteLabel = new Label(); 
        limiteLabel.setText("Limite do cartão"); 
        limiteLabel.setFont(Font.font("Ariel Black", 15)); 
        limiteLabel.setTextFill(Color.BLUE); 
        grid.add(limiteLabel, 1, 3); 
        
        Label tipoLabel = new Label(); 
        tipoLabel.setText("Tipo do cartão"); 
        tipoLabel.setFont(Font.font("Ariel Black", 15)); 
        tipoLabel.setTextFill(Color.BLUE); 
        grid.add(tipoLabel, 1, 4); 
         
        //inicia e add textField
        bandeiraTextField = new TextField(); 
        bandeiraTextField.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE); 
        bandeiraTextField.setText(""); 
        grid.add(bandeiraTextField, 2, 1 ); 
        
        codigoTextField = new TextField(); 
        codigoTextField.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
        codigoTextField.setText(""); 
        grid.add(codigoTextField, 2, 2); 
        
        limiteTextField = new TextField(); 
        limiteTextField.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
        limiteTextField.setText(""); 
        grid.add(limiteTextField, 2, 3); 
        
        HBox box = new HBox(); 
        box.setSpacing(10); 
        
        saveButton = new Button(); 
        saveButton.setText("Salvar"); 
        saveButton.setMaxSize(80, 22);
        saveButton.setOnAction(new CadastraCartao.SaveButtonHandler()); 
        
        box.getChildren().add(saveButton); 
        grid.add(box, 2, 4); 
        
        return grid; 
    }
    
	private TableView createTableCard()
    {
        TableColumn columnBandeira = new TableColumn("Bandeira"); 
        TableColumn columnNumber = new TableColumn("Código"); 
        TableColumn columnLimite = new TableColumn("Limite");  
        TableView table = new TableView(); 
        table.setMaxSize(240, 200);
        
         //carrega e adiciona itens para a tabela
        ObservableList<Cartao> cardList =
                FXCollections.observableArrayList((ArrayList<Cartao>)handler.getCardList());
        
        columnBandeira.setCellValueFactory(
                new PropertyValueFactory<Cartao, String>("bandeira"));
        
        columnNumber.setCellValueFactory(
                new PropertyValueFactory<Cartao, String>("codigo"));
        
        columnLimite.setCellValueFactory(   
                new PropertyValueFactory<Cartao, String>("limite"));
        
        table.getColumns().addAll(columnBandeira, columnNumber, 
               columnLimite); 
        
     
        table.setItems(cardList);
        
        table.setOnMouseClicked(new EventHandler<MouseEvent>()
        {
           @Override
           public void handle(MouseEvent event)
           {
               gridAlteraCartao.setVisible(true); 
               
               cardSelected = 
                       (Cartao)tableCard.getSelectionModel().getSelectedItem();
               
               if(cardSelected != null)
               {
                    alteraBandeiraTextField.setText(cardSelected.getBandeira()); 
                    alteraCodigoTextField.setText(cardSelected.getCodigo()); 
                    alteraLimiteTextField.setText(String.valueOf(
                          cardSelected.getLimite()));
               }
           }
        });
        
        return table; 
        
    }
    
    private GridPane alteraCartao()
    {
        final GridPane grid = new GridPane(); 
        
        for(int i = 0; i < 3; i++)
            grid.add(new Rectangle(30, 15, Color.TRANSPARENT), i, 0); 
        
        alteraBandeiraTextField = new TextField(); 
        alteraBandeiraTextField.setMaxSize(100, 30); 
        grid.add(alteraBandeiraTextField,0, 1); 
        
        alteraCodigoTextField = new TextField(); 
        alteraCodigoTextField.setMaxSize(100, 30); 
        grid.add(alteraCodigoTextField, 1, 1); 
        
        alteraLimiteTextField = new TextField(); 
        alteraLimiteTextField.setMaxSize(100, 30); 
        grid.add(alteraLimiteTextField, 2, 1); 
           
        alteraButton = new Button(); 
        alteraButton.setText("Alterar"); 
        alteraButton.setOnAction(new CadastraCartao.UpdateButtonHandler()); 
        
        grid.add(alteraButton, 1, 2); 
        
        cancelaButton = new Button(); 
        cancelaButton.setText("Cancelar"); 
        cancelaButton.setMaxSize(80, 22); 
        cancelaButton.setOnAction(new EventHandler<ActionEvent>()
        {
           @Override
           public void handle(ActionEvent event)
           {
               grid.setVisible(false); 
               alteraBandeiraTextField.setText(null); 
               alteraCodigoTextField.setText(null);    
               alteraLimiteTextField.setText(null); 
           }
        });
        grid.add(cancelaButton, 2, 2); 
        
        deletaButton = new Button(); 
        deletaButton.setText("Apagar"); 
        deletaButton.setMaxSize(80, 22); 
        deletaButton.setOnAction(new CadastraCartao.DeletButtonHandler());
        grid.add(deletaButton, 2, 3); 
        
        grid.setHgap(10); 
        grid.setVgap(10); 
        grid.setVisible(false);
        
        return grid; 
    }
    
    //metodo para validar campos de entrada de dados
    private Boolean validaForm(String button)
    {
        if(button.equals("save"))
        {
            Boolean bandeira = bandeiraTextField.getText().matches(
                "[A-Za-z][ A-Za-z]*");
            Boolean codigo = codigoTextField.getText().matches("[0-9]*"); 
        
            if(bandeira && codigo)
                return true; 
            else 
                return false;
        }
        else
            if(button.equals("update"))
            {
                
                Boolean bandeira = alteraBandeiraTextField.getText().matches(
                    "[A-Za-z][ A-Za-z]*");
                Boolean codigo = alteraCodigoTextField.getText().matches("[0-9]*"); 
        
                if(bandeira && codigo)
                  return true; 
                else 
                  return false;
            }
        
        return false; 
    }
    
    //classe interna para o tratamento de enventos do botão salvar
    private class SaveButtonHandler implements EventHandler<ActionEvent>
    {
        @Override
        public void handle(ActionEvent event)
        {
            if(validaForm("save"))
            {
                boolean sentinela = true; 
                Integer result = 0; 
                try
                {
                    Cartao card = new Cartao();
                    do
                    {
                        card.setBandeira(bandeiraTextField.getText());
                        card.setCodigo(codigoTextField.getText()); 
                        card.setLimite(Float.parseFloat(limiteTextField.getText()));
                        sentinela = false;
                        
                    }while(sentinela); 
                     
                    result = handler.updateTables(card, "insert");
                    if(result >=0)
                        JOptionPane.showMessageDialog(null, 
                                "Cartao inserido com sucesso."); 
                }
                catch(NumberFormatException exception)
                {
                    JOptionPane.showMessageDialog(null, 
                            "Digite um número no campo limite. "); 
                }
                
                initPane(); 
            }
            else
                JOptionPane.showMessageDialog(null, 
                        "Preencha todos os campos."); 
        
        }
    }
    
    private class UpdateButtonHandler implements EventHandler<ActionEvent>
    {
        @Override
        public void handle(ActionEvent event)
        {
            if(validaForm("update"))
            {
                boolean sentinela = true; 
                Integer result = 0; 
                try
                {
                    do
                    {
                        cardSelected.setBandeira(alteraBandeiraTextField.getText());
                        cardSelected.setCodigo(alteraCodigoTextField.getText()); 
                        cardSelected.setLimite(Float.parseFloat(
                                alteraLimiteTextField.getText()));
                        sentinela = false; 
                    }while(sentinela); 
                    
                    result = handler.updateTables(cardSelected, "update");
                    
                    if(result >= 0)
                        JOptionPane.showMessageDialog(null, 
                                "Cartão alterado com sucesso."); 
                }
                catch(NumberFormatException exception)
                {
                    JOptionPane.showMessageDialog(null, 
                            "Digite um número no campo limite. "); 
                }
                
                initPane(); 
            }
            else
                JOptionPane.showMessageDialog(null,
                        "Preencha todos os campos."); 
        }
    }
    
    private class DeletButtonHandler implements EventHandler<ActionEvent>
    {
        @Override
        public void handle(ActionEvent event)
        {
            Integer result = 0; 
            
            result = handler.updateTables(cardSelected, "delet"); 
            
            if(result <= 0)
                JOptionPane.showMessageDialog(null, 
                        "O cartão só poderá ser apagado se não existir"
                        + " movimentações pertencentes a ele!"); 
            else
            {
                JOptionPane.showMessageDialog(null, 
                        "Cartão apagado com sucesso.");
                initPane(); 
            }
        }
    }
}
